package com.jyxd.web.controller.basic;

import com.jyxd.web.dao.basic.MonitorLifeDataDao;
import com.jyxd.web.data.basic.VitalSignMerge;
import com.jyxd.web.data.user.User;
import com.jyxd.web.mq.HisViewProduction;
import com.jyxd.web.service.assessment.basic.AbpService;
import com.jyxd.web.service.assessment.basic.BloodSugarService;
import com.jyxd.web.service.assessment.basic.VitalSignMergeService;
import com.jyxd.web.service.dictionary.CommentItemService;
import com.jyxd.web.service.hisview.dto.HisViewDataDto;
import com.jyxd.web.util.HttpCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.jyxd.web.config.ConstantConfig.*;
import static com.jyxd.web.util.DateUtil.*;

@Api(tags = "生命体征表出入量2合一相关接口")
@Controller
@RequestMapping(value = "/vitalSignMerge")
public class VitalSignMergeController {

    private static Logger logger = LoggerFactory.getLogger(VitalSignMergeController.class);

    @Autowired
    private VitalSignMergeService vitalSignMergeService;

    @Autowired
    private CommentItemService commentItemService;
    @Autowired
    private MonitorLifeDataDao monitorLifeDataDao;
    @Autowired
    private BloodSugarService bloodSugarService;
    @Autowired
    private AbpService abpService;

    @Autowired
    private HisViewProduction hisViewProduction;


    /**
     * 增加一条生命体征表记录
     *
     * @return
     */
    @ApiOperation("添加")
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    @ResponseBody
    public String insert(@RequestBody VitalSignMerge vitalSign, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "添加失败");
        if (vitalSignMergeService.saveData(vitalSign, session)) {
            json.put("code", HttpCode.OK_CODE.getCode());
            json.put("msg", "添加成功");
        }
        return json.toString();
    }

    /**
     * 更新生命体征表记录状态
     *
     * @param
     * @return
     */
    @ApiOperation("修改")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public String update(@RequestBody VitalSignMerge vitalSign, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        User user = (User) session.getAttribute("user");
        if (vitalSign.getId() != null && !"".equals(vitalSign.getId())) {
            VitalSignMerge vitalSignNew = vitalSignMergeService.queryData(vitalSign.getId());
            vitalSign.setStatus(1);
            vitalSign.setUpdateTime(new Date());
            vitalSign.setOperatorCodeUpdate(user.getId());
            vitalSign.setOperatorCodeUpdateName(user.getUserName());
            vitalSignMergeService.update(vitalSign);
            // 修改时生命体征时，修改血糖单
            vitalSignMergeService.syncBloodGlucose(vitalSign);
            // 修改时生命体征时，修改无创血压单
            vitalSignMergeService.syncArts(vitalSign);
            // 修改时生命体征时，新增护理记录数据到数据中心
            hisViewProduction.put(new HisViewDataDto(HIS_VIEW_EVENT_DC_HlLCZJL_BZBWHL, vitalSign));
            // 修改时生命体征时，新增护理观察数据到数据中心
            hisViewProduction.put(new HisViewDataDto(HIS_VIEW_EVENT_DC_HLCZJL_BZBWHL_HLGC, vitalSign));
            // 修改时生命体征时，新增体征记录数据到数据中心
            hisViewProduction.put(new HisViewDataDto(HIS_VIEW_EVENT_DC_ICU_DAT_TZJL, vitalSign));
            json.put("msg", "更新成功");
        } else {
            json.put("msg", "更新失败");
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 删除生命体征表记录
     *
     * @param
     * @return
     */
    @ApiOperation("删除")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public String delete(@RequestBody VitalSignMerge vitalSign) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "删除失败");
        if (vitalSign.getId() != null && !"".equals(vitalSign.getId())) {
            VitalSignMerge vitalSignNew = vitalSignMergeService.queryData(vitalSign.getId());
            if (vitalSignNew != null) {
                vitalSignNew.setStatus(-1);
                vitalSignMergeService.update(vitalSignNew);
                bloodSugarService.deleteByRelevancyId(vitalSignNew.getId());
                abpService.deleteByRelevancyId(vitalSignNew.getId());
                json.put("msg", "删除成功");
            } else {
                json.put("msg", "删除失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据条件分页查询生命体征表记录列表（也可以不分页）
     *
     * @param map
     * @return
     */
    @ApiOperation("查询")
    @RequestMapping(value = "/queryList", method = RequestMethod.POST)
    @ResponseBody
    public String queryList(@RequestBody(required = false) Map<String, Object> map) throws ParseException {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        if (!map.containsKey("hour")) {
            json.put("msg", "查询时间跨度小时为空，查询失败");
            return json.toString();
        }
        Date endTime = getLaterHoursDate(yyyyMMddHHmmssSdfToDate(String.valueOf(map.get("startTime"))), Long.valueOf(String.valueOf(map.get("hour"))));
        map.put("endTime", yyyyMMddHHmmssSdfToString(endTime));
        if (map != null && map.containsKey("start")) {
            int totalCount = vitalSignMergeService.queryNum(map);
            map.put("start", ((int) map.get("start") - 1) * (int) map.get("size"));
            json.put("totalCount", totalCount);
        }
        List<VitalSignMerge> list = vitalSignMergeService.queryList(map);
        if (list != null && list.size() > 0) {
            json.put("msg", "查询成功");
            json.put("data", JSONArray.fromObject(list));
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 获取有创血压的列表页面
     */
    @ApiOperation("获取有创血压的列表页面")
    @RequestMapping(value = "/queryABPList", method = RequestMethod.POST)
    @ResponseBody
    public String queryABPList(@RequestBody(required = false) Map<String, Object> map) throws CloneNotSupportedException {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        if (map != null && map.containsKey("start")) {
            int totalCount = vitalSignMergeService.queryNum(map);
            map.put("start", ((int) map.get("start") - 1) * (int) map.get("size"));
            double maxWeek = totalCount / (int) map.get("size");
            int maxWeek_ = (int) Math.ceil(maxWeek);
            json.put("maxWeek", maxWeek_);
        }
        List<VitalSignMerge> list = vitalSignMergeService.queryList(map);
        VitalSignMerge entity = new VitalSignMerge();
        if (list != null && list.size() > 0) {
            if (list.size() < (int) map.get("size")) {
                int count = (int) map.get("size") - list.size();
                for (int i = 0; i < count; i++) {
                    list.add((VitalSignMerge) entity.clone());
                }
            }
        } else {
            int count = (int) map.get("size");
            for (int i = 0; i < count; i++) {
                list.add((VitalSignMerge) entity.clone());
            }
        }
        json.put("msg", "查询成功");
        json.put("data", JSONArray.fromObject(list));
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }
}
